import {
  Card,
  Col,
  Form,
  Input,
  InputNumber,
  Modal,
  message,
  Radio,
  Row,
  Tree,
} from 'antd';
import { forwardRef, useEffect, useImperativeHandle, useState } from 'react';
import { useMenuOptions } from '@/models/global';
import { INPUT_MAX_LENGTH } from '@/pages/const/keys';
import { getDicts } from '@/services/data';
import {
  addRole,
  getRoleInfo,
  getRoleMenuTreeSelect,
  updateRole,
} from '@/services/role';

interface UserFormProps {
  roleId?: string;
  onClose?: (reflash?: boolean) => void;
}

const UserForm = forwardRef<any, UserFormProps>((props, ref) => {
  const { roleId, onClose = () => {} } = props;
  const isEdit = !!roleId;
  const [form] = Form.useForm();
  const [setMenuTreeData] = useMenuOptions();
  // tree展开
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [checkedKeys, setCheckedKeys] = useState<React.Key[]>([]);
  const [updateing, setUpdateing] = useState<boolean>(false);
  // const [treeData, setTreeData] = useState<TreeDataNode[]>([]);
  // const [sexOptions, setSexOptions] = useState<any[]>([]);
  const [sexstatusOptions, setstatusOptions] = useState<any[]>([]);

  // ✅ 暴露方法给父组件
  useImperativeHandle(ref, () => ({
    form, // 暴露 form 实例
    getValues: () => form.getFieldsValue(),
    reset: () => form.resetFields(),
    validate: () => form.validateFields(),
  }));

  const getData = async () => {
    const { checkedKeys } = await getRoleMenuTreeSelect(roleId || '');
    const { data: nData = [] } = await getDicts('sys_normal_disable');
    setCheckedKeys(checkedKeys);

    setstatusOptions(
      nData?.map((i: { dictLabel: any; dictValue: any }) => ({
        label: i.dictLabel,
        value: i.dictValue,
      })),
    );
  };
  // expand
  // const handleExpand = (selected: React.Key[]) => {
  //   console.log("selected", selected, setMenuTreeData);
  //   const allKeys: any = [];
  //   const traverse = (nodes: TreeDataNode[]) => {
  //     nodes.forEach((node) => {
  //       console.log(node.key);
  //       allKeys.push(node.key as React.Key);
  //       if (node.children) {
  //         traverse(node.children);
  //       }
  //     });
  //   };

  //   traverse(setMenuTreeData);
  //   console.log(allKeys);
  //   if (selected?.length > 0) {
  //     setExpandedKeys(allKeys);
  //   } else {
  //     setExpandedKeys([]);
  //   }
  // };
  //selectall or unselect all
  // const handleSelectAll = (selected: any[]) => {
  //   if (selected?.length > 0) {
  //     const allKeys: React.Key[] = [];
  //     const traverse = (nodes: TreeDataNode[]) => {
  //       nodes.forEach((node) => {
  //         allKeys.push(node.key as React.Key);
  //         if (node.children) {
  //           traverse(node.children);
  //         }
  //       });
  //     };
  //     traverse(setMenuTreeData);
  //     setCheckedKeys(allKeys);
  //   } else {
  //     setCheckedKeys([]);
  //   }
  // };
  useEffect(() => {
    (async () => {
      getData();

      if (roleId === undefined) {
        return;
      }
      const { data } = await getRoleInfo(roleId);
      const { roleSort, roleKey, roleName, remark, status } = data || {};
      form.setFieldsValue({
        menuIds: checkedKeys || [],
        menuCheckStrictly: [true],
        roleSort,
        roleKey,
        roleName,
        remark,
        status,
      });
    })();
  }, [roleId]);

  const sumbit = async () => {
    await form.validateFields();
    const values = form.getFieldsValue();
    const {
      status,
      remark,
      roleSort,
      roleName,
      roleKey,
      menuCheckStrictly,
      ...rest
    } = values;
    const menuIds = checkedKeys || [];
    const submitData = {
      ...rest,
      deptCheckStrictly: true,
      roleId,
      roleSort,
      remark,
      roleName,
      roleKey,
      status,
      menuIds,
      menuCheckStrictly:
        menuCheckStrictly !== undefined ? menuCheckStrictly[0] : undefined,
    };
    setUpdateing(true);
    const { code } = !roleId
      ? await addRole(submitData)
      : await updateRole(submitData);
    if (code === 200) {
      message.success('操作成功');
      onClose(true);
    } else {
      // message.error(msg || '操作失败');
    }
    setUpdateing(false);
  };
  return (
    <Modal
      width={500}
      title={isEdit ? '修改角色' : '新增角色'}
      open={true}
      onOk={sumbit}
      okButtonProps={{
        disabled: updateing,
      }}
      cancelButtonProps={{
        disabled: updateing,
      }}
      onCancel={() => {
        onClose();
      }}
    >
      <Form form={form} labelCol={{ span: 5 }} wrapperCol={{ span: 24 }}>
        <Row gutter={16}>
          <Col span={24}>
            <Form.Item
              label="角色代码"
              name="roleKey"
              // tooltip="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasRole('admin')`)"
              rules={[
                {
                  required: true,
                },
              ]}
            >
              <Input
                placeholder="请输入权限字符"
                maxLength={INPUT_MAX_LENGTH}
              />
            </Form.Item>
          </Col>
          <Col span={24}>
            <Form.Item
              label="角色名称"
              name="roleName"
              rules={[
                {
                  required: true,
                },
              ]}
            >
              <Input
                placeholder="请输入角色名称"
                maxLength={INPUT_MAX_LENGTH}
              />
            </Form.Item>
          </Col>

          <Col span={24} hidden>
            {/* 校验 */}
            <Form.Item
              label="角色顺序"
              name="roleSort"
              initialValue={0}
              rules={[
                {
                  required: true,
                },
              ]}
            >
              <InputNumber
                style={{ width: '100%' }}
                placeholder="请输入角色顺序"
              />
            </Form.Item>
          </Col>

          <Col span={24} hidden>
            <Form.Item label="状态" name="status" initialValue={'0'}>
              <Radio.Group options={sexstatusOptions} />
            </Form.Item>
          </Col>
          <Col span={24}>
            <Form.Item label="简介" name="remark" wrapperCol={{ span: 24 }}>
              <Input.TextArea
                rows={4}
                placeholder="请输入简介"
                showCount
                maxLength={200}
              />
            </Form.Item>
          </Col>
          <Col span={24}>
            <Form.Item label="菜单权限">
              <Card size="small">
                <div
                  className="div"
                  style={{
                    height: 150,
                    overflow: 'auto',
                  }}
                >
                  <Tree
                    checkable
                    //展开
                    defaultExpandAll
                    expandedKeys={expandedKeys}
                    checkedKeys={checkedKeys}
                    treeData={setMenuTreeData}
                    onExpand={(expandedKeys) => {
                      setExpandedKeys(expandedKeys);
                    }}
                    onCheck={(checkedKeys) => {
                      setCheckedKeys(checkedKeys as React.Key[]);
                      // form.setFieldValue("menuIds", checkedKeys);
                    }}
                  />
                </div>
              </Card>
              {/* <Row gutter={[gutter, gutter]}>
                <Col span={24} style={{ width: "100%" }}>
                  <Row>
                    <Col>
                      <Checkbox.Group
                        options={menuOptions?.slice(0, 1)}
                        onChange={(checked) => {
                          handleExpand(checked);
                        }}
                      />
                    </Col>
                    <Col>
                      <Checkbox.Group
                        options={menuOptions?.slice(1, 2)}
                        onChange={(checked) => {
                          handleSelectAll(checked);
                        }}
                      />
                    </Col>
                    <Col>
                      <Form.Item name="menuCheckStrictly" noStyle>
                        <Checkbox.Group options={menuOptions.slice(2)} />
                      </Form.Item>
                    </Col>
                  </Row>
                </Col>
                <Col span={24}>
                  <Form.Item name="menuIds" noStyle>

                  </Form.Item>
                </Col>
              </Row> */}
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </Modal>
  );
});

export default UserForm;
